package com.qcc.cashier.react.module;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.RequestException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;
import com.qcc.cashier.print.PrintHelper;
import com.qcc.cashier.utils.ImageUtils;
import android.print.pdf.*;
import android.printservice.*;

public class PrintModule extends ReactContextBaseJavaModule {

    private PrintHelper mHelper;

    public PrintModule(@NonNull ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @NonNull
    @Override
    public String getName() {
        return "PrintModule";
    }

    @ReactMethod
    public void printImg(String base64, Promise promise) {
        login(promise);
        if (mHelper == null) {
            mHelper = new PrintHelper();
        }
        String printPath = ImageUtils.saveTo(ImageUtils.getBitmapBase64(base64), "print");
        mHelper.startPrint(printPath).subscribe(result -> {
            if (result) {
                promise.resolve(true);
                DeviceService.logout();
            } else {
                login(promise);
                promise.reject("500", "远程失败");
            }
        }, err -> {
            promise.reject(err);
        });
    }

    private void login(Promise promise) {
        try {
            DeviceService.login(getReactApplicationContext());
        } catch (ServiceOccupiedException e) {
            e.printStackTrace();
            promise.reject(e);
        } catch (ReloginException e) {
            e.printStackTrace();
            promise.reject(e);
        } catch (UnsupportMultiProcess unsupportMultiProcess) {
            unsupportMultiProcess.printStackTrace();
            promise.reject(unsupportMultiProcess);
        } catch (RequestException e) {
            e.printStackTrace();
            promise.reject(e);
        }
    }
}
